const axios = require('axios');
const qs = require('qs');
const CryptJS = require("crypto-js");

//4399登录, 返回Cookie
const login_4399 = (username, password) => {
    const data = {
        loginFrom: 'uframe',
        postLoginHandler: 'default',
        layoutSelfAdapting: 'false',
        externalLogin: 'qq',
        displayMode: 'embed',
        layout: 'vertical',
        bizId: '1199000602',
        appId: 'u4399',
        gameId: '',
        css: '//uc.img4399.com/sso/css/ptlogin.css?20230714',
        redirectUrl: '',
        sessionId: '',
        mainDivId: 'embed_login_div',
        includeFcmInfo: 'false',
        level: '8',
        regLevel: '8',
        userNameLabel: '4399用户名',
        userNameTip: '请输入4399用户名',
        welcomeTip: '欢迎回到4399',
        sec: 1,
        password: CryptJS.AES.encrypt(password, 'lzYW5qaXVqa').toString(),
        username: username,
        autoLogin: 'on'
    };
    return new Promise((resolve, reject) => {
        axios({
            method: 'POST',
            url: 'https://ptlogin.4399.com/ptlogin/login.do?v=1',
            data: qs.stringify(data),
            headers: {"Content-Type": 'application/x-www-form-urlencoded'},
        }).then((res) => {
            const resHeader = res.headers['set-cookie'];
            let retData = [];
            if (resHeader != null) {
                for (let i = 0; i < resHeader.length; i++) {
                    retData.push(resHeader[i].split(";")[0]);
                }
            }
            resolve(retData);
        }).catch((err) => {
            reject(err);
        })
    })
}

//进行授权
const auth_4399 = (cookie) => {
    return new Promise((resolve, reject) => {
        axios({
            method: 'GET',
            url: 'https://u.4399.com/sso/syn-token.html?client_id=a9a16636dbaeb917e2ffb16f0d52006e&redirect=https%3A%2F%2Fwww.zxwyouxi.com%2Fintermodal%2Fuser%2Flogin%2Fzxwyouxi%3FcallbackUrl%3Dhttps%253A%252F%252Fwww.zxwyouxi.com%252Fg%252F100053785',
            headers: {"Cookie": cookie},
        }).then((res) => {
            let resData = res.data;
            let retData = {};
            if (resData.c === 200) {
                let str = resData.d.redirect;
                const arr = str.substring(str.indexOf('?') + 1).split('&');
                for (let i = 0; i < arr.length; i++) {
                    const temp = arr[i].split('=');
                    retData[temp[0]] = temp[1];
                }
                retData['cookie'] = res.headers['set-cookie'][0].split(";")[0];
            }
            resolve(retData);
        }).catch((err) => {
            reject(err);
        })
    })
}

//获取checkObj信息
const getUserData_4399 = (userId, token, cookie) => {
    const data = {
        gameId: '100053785',
        authType: 'token',
        userId: userId,
        accessToken: token,
        pcwap: '',
        all: ''
    };
    return new Promise((resolve, reject) => {
        axios({
            method: 'POST',
            url: 'https://h.api.4399.com/intermodal/user/grant2',
            data: qs.stringify(data),
            headers: {"Cookie": cookie, "Content-Type": 'application/x-www-form-urlencoded'},
        }).then((res) => {
            let resData = res.data;
            let retData = {};
            if (resData.code === 10000) {
                let str = resData.data.game.gameUrl;
                const arr = str.substring(str.indexOf('?') + 1).split('&');
                for (let i = 0; i < arr.length; i++) {
                    const temp = arr[i].split('=');
                    retData[temp[0]] = temp[1];
                }
            }
            resolve(retData);
        }).catch((err) => {
            reject(err);
        })
    })
}


module.exports = {
    login_4399,
    auth_4399,
    getUserData_4399
}